package xrate

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 创建批次信息
//
//	bat	批次信息
//	uid	用户ID
func BatchCreate(bat *Batch, uid uint) error {
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	if uid <= 0 {
		return xerror.New("用户ID不能为空")
	}
	if bat.Name == "" {
		return xerror.New("批次名称不能为空")
	}
	if bat.Status != 0 && bat.ID == 0 {
		return xerror.New("禁止直接插入正式数据")
	}
	if bat.UserId == 0 {
		bat.UserId = uid
	}
	if bat.StartTime == "" {
		bat.StartTime = time.Now().Format(time.DateTime)
	}
	if bat.EndTime == "" {
		bat.EndTime = "2099-12-31"
	}
	if bat.CreatedAt == "" {
		bat.CreatedAt = time.Now().Format(time.DateTime)
	}
	bat.UpdatedAt = time.Now().Format(time.DateTime)
	err := _default.DB.Save(bat).Error
	if err != nil {
		return err
	}
	// 缓存写入
	xcache.Remove(xcache.Key("xrate.rate_batch", bat.ID))
	xcache.SetStruct(xcache.Key("xrate.batch_info", bat.ID), bat)
	return nil
}
